<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :bodyStyle="{ maxHeight: '70vh', overflow: 'auto' }"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <div style="margin-bottom: 16px">
        <a-descriptions :column="3" bordered>
          <a-descriptions-item label="工种编码">{{ workTypeInfo.workTypeCode }}</a-descriptions-item>
          <a-descriptions-item label="工种名称">{{ workTypeInfo.workTypeName }}</a-descriptions-item>
          <a-descriptions-item label="状态">{{ workTypeInfo.status_dictText }}</a-descriptions-item>
        </a-descriptions>
      </div>

      <div class="table-operator" style="margin-bottom: 16px">
        <a-button type="primary" icon="plus" @click="handleAdd">新增计件标准</a-button>
        <a-button type="primary" icon="download" @click="handleExport">导出</a-button>
        <a-upload
          name="file"
          :showUploadList="false"
          :multiple="false"
          :headers="tokenHeader"
          :action="importExcelUrl"
          @change="handleImportExcel"
        >
          <a-button type="primary" icon="import">导入</a-button>
        </a-upload>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="batchDel"> <a-icon type="delete" />删除 </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a> 项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ x: 1200, y: 400 }"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="baseRate" slot-scope="text">
          <span style="color: #1890ff; font-weight: bold">¥{{ text }}</span>
        </template>

        <template slot="difficultyFactor" slot-scope="text">
          <a-tag color="orange">{{ text }}倍</a-tag>
        </template>

        <template slot="qualityBonus" slot-scope="text">
          <a-tag color="green">{{ text }}%</a-tag>
        </template>

        <template slot="efficiencyBonus" slot-scope="text">
          <a-tag color="blue">{{ text }}%</a-tag>
        </template>

        <template slot="status" slot-scope="text">
          <a-tag :color="text == '1' || text == 1 ? 'green' : 'red'">
            {{ text == '1' || text == 1 ? '有效' : '无效' }}
          </a-tag>
        </template>

        <template slot="isDefault" slot-scope="text">
          <a-badge v-if="text == 1" status="success" text="是" />
          <a-badge v-else status="default" text="否" />
        </template>

        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a style="color: red">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-spin>

    <!-- 计件标准编辑模态框 -->
    <piece-rate-standard-modal ref="standardModal" @ok="standardModalOk"></piece-rate-standard-modal>
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import PieceRateStandardModal from './PieceRateStandardModal'

export default {
  name: 'WorkTypePieceRateModal',
  mixins: [JeecgListMixin],
  components: {
    PieceRateStandardModal,
  },
  data() {
    return {
      title: '计件标准配置',
      visible: false,
      confirmLoading: false,
      workTypeInfo: {},
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '产品类别',
          align: 'center',
          dataIndex: 'productCategory',
          width: 120,
        },
        {
          title: '基础单价(元)',
          align: 'center',
          dataIndex: 'baseRate',
          width: 120,
          scopedSlots: { customRender: 'baseRate' },
        },
        {
          title: '难度系数',
          align: 'center',
          dataIndex: 'difficultyFactor',
          width: 100,
          scopedSlots: { customRender: 'difficultyFactor' },
        },
        {
          title: '质量奖励(%)',
          align: 'center',
          dataIndex: 'qualityBonus',
          width: 100,
          scopedSlots: { customRender: 'qualityBonus' },
        },
        {
          title: '效率奖励(%)',
          align: 'center',
          dataIndex: 'efficiencyBonus',
          width: 100,
          scopedSlots: { customRender: 'efficiencyBonus' },
        },
        {
          title: '生效日期',
          align: 'center',
          dataIndex: 'effectiveDate',
          width: 120,
        },
        {
          title: '失效日期',
          align: 'center',
          dataIndex: 'expiryDate',
          width: 120,
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 80,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '是否默认',
          align: 'center',
          dataIndex: 'isDefault',
          width: 100,
          scopedSlots: { customRender: 'isDefault' },
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/mes/pieceRateStandard/getByWorkType',
        delete: '/mes/pieceRateStandard/delete',
        deleteBatch: '/mes/pieceRateStandard/deleteBatch',
        exportXlsUrl: '/mes/pieceRateStandard/exportXls',
        importExcelUrl: 'mes/pieceRateStandard/importExcel',
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    show(record) {
      this.workTypeInfo = record
      this.visible = true
      this.queryParam = {
        workTypeId: record.id,
      }
      this.loadData(1)
    },
    // 重写loadData方法以适配getByWorkType接口
    loadData(arg) {
      if (!this.queryParam.workTypeId) {
        return
      }
      this.loading = true
      const params = {
        workTypeId: this.queryParam.workTypeId,
      }
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result || []
            this.ipagination.total = this.dataSource.length
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleOk() {
      this.handleCancel()
    },
    handleCancel() {
      this.visible = false
      this.workTypeInfo = {}
      this.dataSource = []
      this.selectedRowKeys = []
    },
    handleAdd() {
      this.$refs.standardModal.add(this.workTypeInfo)
    },
    handleEdit(record) {
      this.$refs.standardModal.edit(record)
    },
    handleDelete(id) {
      this.deleteAction(this.url.delete, { id: id }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        }
      })
    },
    batchDel() {
      this.batchDelAction(this.url.deleteBatch, this.selectedRowKeys).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.onClearSelected()
          this.loadData()
        }
      })
    },
    handleExport() {
      let paramsStr = encodeURI(JSON.stringify({ workTypeId: this.workTypeInfo.id }))
      let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?params=${paramsStr}`
      window.open(url)
    },
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(`${info.file.name} 文件上传成功`)
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败`)
      }
    },
    standardModalOk() {
      this.loadData()
    },
  },
}
</script>

<style scoped>
</style>
